import { ref, computed } from 'vue'
import type { GameState } from './useGameState'

interface GameRecording {
  id: string
  date: Date
  moves: {
    from: { row: number, col: number }
    to: { row: number, col: number }
    piece: string
    captured?: string
    promotion?: string
    check?: boolean
    checkmate?: boolean
    time?: number
  }[]
  result?: string
  whitePlayer: string
  blackPlayer: string
  timeControl: {
    initial: number
    increment: number
  }
  tags: {
    event?: string
    site?: string
    round?: string
    eco?: string
  }
}

export function useGameRecorder() {
  const recordings = ref<GameRecording[]>([])
  const currentRecording = ref<GameRecording | null>(null)
  const isRecording = ref(false)

  const loadRecordings = () => {
    const saved = localStorage.getItem('chessRecordings')
    if (saved) {
      recordings.value = JSON.parse(saved)
    }
  }

  const saveRecordings = () => {
    localStorage.setItem('chessRecordings', JSON.stringify(recordings.value))
  }

  const startRecording = (
    whitePlayer: string,
    blackPlayer: string,
    timeControl: { initial: number, increment: number }
  ) => {
    currentRecording.value = {
      id: Date.now().toString(),
      date: new Date(),
      moves: [],
      whitePlayer,
      blackPlayer,
      timeControl,
      tags: {}
    }
    isRecording.value = true
  }

  const recordMove = (
    from: { row: number, col: number },
    to: { row: number, col: number },
    piece: string,
    gameState: GameState
  ) => {
    if (!isRecording.value || !currentRecording.value) return

    currentRecording.value.moves.push({
      from,
      to,
      piece,
      captured: gameState.capturedPieces.white[gameState.capturedPieces.white.length - 1] || 
               gameState.capturedPieces.black[gameState.capturedPieces.black.length - 1],
      check: false, // 需要从游戏状态获取
      checkmate: false, // 需要从游戏状态获取
      time: gameState.gameTime[piece.includes('white') ? 'white' : 'black']
    })
  }

  const stopRecording = (result?: string) => {
    if (currentRecording.value) {
      currentRecording.value.result = result
      recordings.value.push(currentRecording.value)
      saveRecordings()
    }
    currentRecording.value = null
    isRecording.value = false
  }

  const deleteRecording = (id: string) => {
    recordings.value = recordings.value.filter(r => r.id !== id)
    saveRecordings()
  }

  const getRecording = (id: string) => {
    return recordings.value.find(r => r.id === id)
  }

  const addTag = (id: string, key: keyof GameRecording['tags'], value: string) => {
    const recording = recordings.value.find(r => r.id === id)
    if (recording) {
      recording.tags[key] = value
      saveRecordings()
    }
  }

  const recentRecordings = computed(() => {
    return [...recordings.value]
      .sort((a, b) => new Date(b.date).getTime() - new Date(a.date).getTime())
      .slice(0, 10)
  })

  const getRecordingsByPlayer = (playerName: string) => {
    return recordings.value.filter(r => 
      r.whitePlayer === playerName || r.blackPlayer === playerName
    )
  }

  const exportRecording = (id: string, format: 'PGN' | 'JSON') => {
    const recording = getRecording(id)
    if (!recording) return null

    if (format === 'PGN') {
      // 转换为PGN格式
      const headers = [
        ['Event', recording.tags.event || '?'],
        ['Site', recording.tags.site || '?'],
        ['Date', recording.date.toISOString().split('T')[0]],
        ['Round', recording.tags.round || '1'],
        ['White', recording.whitePlayer],
        ['Black', recording.blackPlayer],
        ['Result', recording.result || '*']
      ]

      const headerStr = headers
        .map(([key, value]) => `[${key} "${value}"]`)
        .join('\n')

      const moveStr = recording.moves
        .map((move, i) => {
          const notation = convertMoveToAlgebraic(move)
          return i % 2 === 0 ? `${Math.floor(i/2) + 1}. ${notation}` : notation
        })
        .join(' ')

      return `${headerStr}\n\n${moveStr} ${recording.result || '*'}`
    }

    return JSON.stringify(recording, null, 2)
  }

  const convertMoveToAlgebraic = (move: GameRecording['moves'][0]): string => {
    const files = 'abcdefgh'
    const ranks = '87654321'
    
    const from = `${files[move.from.col]}${ranks[move.from.row]}`
    const to = `${files[move.to.col]}${ranks[move.to.row]}`
    
    let notation = ''
    
    if (move.piece.includes('king') && Math.abs(move.from.col - move.to.col) === 2) {
      // 王车易位
      return move.to.col > move.from.col ? 'O-O' : 'O-O-O'
    }
    
    if (!move.piece.includes('pawn')) {
      notation += move.piece[0].toUpperCase()
    }
    
    if (move.captured) {
      notation += move.piece.includes('pawn') ? from[0] : ''
      notation += 'x'
    }
    
    notation += to
    
    if (move.promotion) {
      notation += `=${move.promotion[0].toUpperCase()}`
    }
    
    if (move.checkmate) {
      notation += '#'
    } else if (move.check) {
      notation += '+'
    }
    
    return notation
  }

  return {
    recordings,
    currentRecording,
    isRecording,
    loadRecordings,
    startRecording,
    recordMove,
    stopRecording,
    deleteRecording,
    getRecording,
    addTag,
    recentRecordings,
    getRecordingsByPlayer,
    exportRecording
  }
} 